package com.ruicar.afs.cloud.apply.pre.loan.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.apply.common.dto.ProductInfoDTO;
import com.ruicar.afs.cloud.apply.common.entity.ApplyCarDetails;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOrderInfo;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyReportCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.vo.ApplyReportVO;
import com.ruicar.afs.cloud.bizcommon.business.bean.FinanceCalculatorBean;
import com.ruicar.afs.cloud.bizcommon.business.bean.FinanceInfoBean;
import com.ruicar.afs.cloud.bizcommon.business.dto.CalculatorDTO;
import com.ruicar.afs.cloud.bizcommon.business.dto.CalculatorListDTO;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinDiscountDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyDiscountDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyFinancingItemsService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 金融产品
 * @author: sijun.yu
 * @date: 2020/5/16 13:48
 */
@Slf4j
@RestController
@RequestMapping(value = "product")
@AllArgsConstructor
public class ApplyProductController {

    private ApplyCostDetailsService costDetailsService;
    private ApplyFinancingItemsService financingItemsService;
    private ApplyDiscountDetailsService discountDetailsService;
    private ApplyReportService reportService;
    private ApplyProductService productService;
    private ApplyOrderInfoService applyOrderInfoService;
    private ApplyCarDetailsService applyCarDetailsService;
    private ApplyModifyHistoryService modifyHistoryService;

    /**
     * 查询产品列表
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/queryProductSelectList")
    @ApiOperation("查询产品列表")
    public IResponse queryProductSelectList(@RequestBody CalculatorDTO condition) {

        JSONObject jsonObject = productService.queryProductSelectList(condition);
        if (CommonConstants.SUCCESS.equals(jsonObject.getString("code"))) {
            if (0 == jsonObject.getJSONObject("data").getInteger("total")) {
                return IResponse.fail("未匹配到对应产品");
            } else {
                return IResponse.success(jsonObject.getJSONObject("data"));
            }
        } else {
            return IResponse.fail("未匹配到对应产品");
        }
    }

    /**
     * 查询产品详情
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/queryProductDetails")
    @ApiOperation("查询产品详情")
    public IResponse queryProductDetails(@ModelAttribute CalculatorDTO condition) {

        return productService.queryProductDetails(condition);
    }

    /**
     * 产品信息校验
     *
     * @return
     */
    @ApiOperation("产品信息校验")
    @PostMapping(value = "/checkProductInfo")
    public IResponse checkProductInfo(@RequestBody CalculatorListDTO condition) {

        return productService.checkProductInfo(condition);
    }

    /**
     * 获取产品利率
     *
     * @return
     */
    @ApiOperation("获取产品利率")
    @PostMapping(value = "/getProductRate")
    public IResponse getProductRate(@ModelAttribute CalculatorDTO condition) {

        return productService.getProductRate(condition);
    }

    /**
     * 查询产品列表，传入参数的数据
     *
     * @return
     */
    @ApiOperation("查询产品列表，传入参数的数据")
    @PostMapping(value = "/initProductParam")
    public IResponse initProductParam(@ModelAttribute ApplyReportCondition condition) {

        ApplyReportVO applyReportVO = reportService.initProductParam(condition.getApplyNo());
        return IResponse.success(applyReportVO);
    }

    /**
     * 查询贷款信息【汇总】
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getFinanceCostAll")
    @ApiOperation("查询贷款信息【汇总】")
    public IResponse getFinanceCostAll(@ModelAttribute CalculatorDTO condition) {

        FinanceCalculatorBean vo = null;
        // 资产变更
        if("assetChange".equals(condition.getBusinessFlag())){
            vo = modifyHistoryService.getFinancialProductsForAssetChange(vo,condition);
            if(vo != null){
                return IResponse.success(vo);
            }
        }
        vo = reportService.getFinanceCostAll(vo,condition);
        return IResponse.success(vo);
    }

    /**
     * 融资项目，车款、GPS、保险、购置税、装潢
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getFinancingItems")
    @ApiOperation("融资项目")
    public IResponse getFinancingItems(@ModelAttribute CalculatorDTO condition) {

        String applyNo = condition.getApplyNo();
        List<FinFinancingItems> list = financingItemsService.getFinancingItemsList(condition.getApplyNo(), condition.getCarId());
        List<FinFinancingItems> resultList = new ArrayList<FinFinancingItems>();
        for (int i = 0; i < list.size(); i++) {
            FinFinancingItems financingItems = list.get(i);
            FinFinancingItems items = new FinFinancingItems();
            items.setId(financingItems.getId());
            items.setApplyNo(financingItems.getApplyNo());
            items.setCarId(financingItems.getCarId());
            items.setFinanceItemCode(financingItems.getFinanceItemCode());
            items.setFinanceItemName(financingItems.getFinanceItemName());
            items.setFinanceItemAmt(financingItems.getFinanceItemAmt());
            List<FinFinancingItems> sonList = financingItemsService.getApplyFinancingItemsList(applyNo, financingItems.getId());
            if (sonList != null && sonList.size() > 0) {
                items.setSonList(sonList);
            }
            resultList.add(items);
        }
        return IResponse.success(resultList);
    }

    /**
     * 查询贴息明细列表
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getDiscountDetails")
    @ApiOperation("查询贴息明细列表")
    public IResponse getDiscountDetails(@ModelAttribute CalculatorDTO condition) {

        List<FinDiscountDetails> discountList = discountDetailsService.getDiscountDetailsList(condition.getApplyNo(), condition.getCostType());
        return IResponse.success(discountList);
    }

    /**
     * 保存融资信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/saveCostList")
    @ApiOperation("保存融资信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveCostList(@RequestBody CalculatorListDTO condition) {

        // 调用融资校验接口
        IResponse iResponse = productService.checkProductInfo(condition);
        if (!CommonConstants.SUCCESS.equals(iResponse.getCode())) {
            return iResponse;
        }
        String applyNo = condition.getApplyNo();
        List<FinCostDetails> resultList = productService.saveCostList(applyNo, condition.getCostList());
        return IResponse.success(resultList);
    }

    /**
     * 更新融资信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/updateCostList")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("更新融资列表")
    public IResponse updateCostList(@RequestBody CalculatorListDTO condition) {

        // 调用融资校验接口
        IResponse iResponse = productService.checkProductInfo(condition);
        if (!"0000".equals(iResponse.getCode())) {
            return iResponse;
        }
        String applyNo = condition.getApplyNo();
        List<FinCostDetails> resultList = productService.updateCostList(applyNo, condition.getCostList());
        return IResponse.success(resultList);
    }

    /**
     * 调用计算器生成多个还款计划表
     *
     * @param condition
     * @return
     */
    @ApiOperation("调用计算器")
    @PostMapping("/financeCalculation")
    public IResponse financeCalculation(@RequestBody CalculatorListDTO condition) {

        return productService.financeCalculation(condition.getCostList());
    }

    /**
     * 金融产品-融资计算器-For-App
     *
     * @param condition
     * @return
     */
    @ApiOperation("金融产品-融资计算器")
    @PostMapping("/financeProductCalculation")
    public IResponse financeProductCalculation(@RequestBody CalculatorListDTO condition) {

        return productService.financeProductCalculation(condition);
    }

    /**
     * 通过贴息金额倒推客户利率
     *
     * @param condition
     * @return
     */
    @ApiOperation("通过贴息金额倒推客户利率")
    @PostMapping("/getCustRate")
    public IResponse getCustRate(@RequestBody CalculatorDTO condition) {

        return productService.getCustRate(condition);
    }

    /**
     * 获取任意贷还款计划表
     *
     * @return
     */
    @ApiOperation("获取任意贷还款计划表")
    @PostMapping("/getArbitraryRepaymentPlan")
    public IResponse getArbitraryRepaymentPlan(@RequestBody CalculatorDTO condition) {

        return productService.getArbitraryRepaymentPlan(condition);
    }

    /**
     * 搜索附加项目名称
     * @param condition
     * @return
     */
    @ApiOperation("搜索附加项目名称")
    @PostMapping("/queryExtrasInfoSonList")
    public IResponse queryExtrasInfoSonList(@RequestBody ProductInfoDTO condition){

        return productService.queryExtrasInfoSonList(condition);
    }

    /**
     * 获取附条件核准数据
     *
     * @param calculatorDTO
     * @return
     */
    @ApiOperation("获取附条件核准数据")
    @PostMapping("/getConditionApprove")
    public IResponse getConditionApprove(@RequestBody CalculatorDTO calculatorDTO) {
        Map<String, Object> map = new HashMap();
        FinanceCalculatorBean vo = new FinanceCalculatorBean();
        //查询订单表信息
        ApplyOrderInfo orderInfo = this.applyOrderInfoService.getOrderInfoByApplyNo(calculatorDTO.getApplyNo());
        //融资信息
        List<FinCostDetails> costDetailsList = this.costDetailsService.getCostDetailsList(calculatorDTO.getApplyNo());
        //车辆信息
        ApplyCarDetails carDetailsByApplyNo = this.applyCarDetailsService.getCarDetailsByApplyNo(calculatorDTO.getApplyNo());
        // 附加产品
        String isAdditional = WhetherEnum.No.getIndex();
        FinanceInfoBean addProductInfo = costDetailsService.getAddProductInfo(calculatorDTO.getApplyNo(), carDetailsByApplyNo.getId(), ApplyConstants.COST_TYPE_ADD_LOAN);
        if (addProductInfo != null) {
            isAdditional = WhetherEnum.YES.getIndex();
            vo.setIsAdditional(isAdditional);
            vo.setAddProductInfo(addProductInfo);
        }
        // 初始化-车辆价格
        ApplyReportVO reportVO = reportService.initProductParam(calculatorDTO.getApplyNo());
        // 车辆产品
        FinanceInfoBean carProductInfo = costDetailsService.getCarProductInfo(calculatorDTO.getApplyNo(), carDetailsByApplyNo.getId(), ApplyConstants.COST_TYPE_CAR_LOAN);
        // 是否有子产品
        if (carProductInfo != null) {
            FinCostDetails costInfo = carProductInfo.getCostInfo();
            String isSubProduct = costInfo.getIsSubProduct();
            if (WhetherEnum.No.getIndex().equals(isSubProduct)) {
                isAdditional = WhetherEnum.YES.getIndex();
                vo.setIsAdditional(isAdditional);
            }
            vo.setIsSubProduct(isSubProduct);
            // 车辆价格
            costInfo.setContractAmt(reportVO.getSalePrice());
            carProductInfo.setCostInfo(costInfo);
            vo.setCarProductInfo(carProductInfo);
        }
        map.put("orderInfo", orderInfo);
        map.put("costDetailsList", costDetailsList);
        map.put("carDetailsByApplyNo", carDetailsByApplyNo);
        map.put("vo", vo);
        return IResponse.success(map);
    }
}
